package com.battle.pojo.validation;

import com.battle.pojo.valid.Name;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author Joseph.Li
 * @author joseph.li@king-v.com
 * Created in 2022-06-28 16:42
 * 名称校验检测
 */
@Slf4j
@Component
public class NameValidation implements ConstraintValidator<Name, String> {


    private final StringRedisTemplate stringRedisTemplate;

    // 添加一个字段来存储正则表达式
    private String pattern;

    public NameValidation(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public void initialize(Name constraintAnnotation) {
        // 从注解中读取正则表达式
        this.pattern = constraintAnnotation.pattern();
    }

    @Override
    public boolean isValid(String nameField, ConstraintValidatorContext cxt) {

        if (!StringUtils.hasText(nameField)) {
            // we can return true because the @NotNull annotation will be used for null checking
            return true;
        }
        // add your own name validation here
        return nameField.matches(pattern);
    }
}
